package com.seahorse.youliao.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.seahorse.youliao.common.ResponseEntity;
import com.seahorse.youliao.security.JwtUserRedis;
import com.seahorse.youliao.util.IpUtil;
import com.seahorse.youliao.util.JwtTokenUtils;
import com.zengtengpeng.operation.RedissonObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @description: 自定义成功认证
 * @author: Mr.Song
 * @create: 2020-11-25 00:01
 **/
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private static final Long EXPIRE_TIME = 2 * 60 * 60 * 1000L;

    @Autowired
    private RedissonObject redissonObject;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {


        // 生成并返回token给客户端，后续访问携带此token
        String token = JwtTokenUtils.generateToken(authentication);
        JwtUserRedis userDetails = new JwtUserRedis();
        BeanUtils.copyProperties(authentication,userDetails);
        userDetails.setUsername(((UserDetails)authentication.getPrincipal()).getUsername());
        userDetails.setLoginIp(IpUtil.getIpAddr(request));
        userDetails.setLoginLocation(IpUtil.getCityInfo(IpUtil.getIpAddr(request)));
        userDetails.setLoginTime(new Date());
        //放入缓存
        redissonObject.setValue("user:"+token, userDetails, EXPIRE_TIME);
        response.setContentType("application/json; charset=utf-8");
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setResult(token);
        responseEntity.setRemark("登录成功");
        String json = JSONObject.toJSONString(responseEntity);
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();
    }
}
